import { useEffect, useState } from 'react';
import CommonModal from '@/components/CommonModal';
import { Form, Radio, Alert, Space, message } from 'antd';
import { find } from 'lodash';
import { getShippingConfigList, saveOrUpdateVoiceConfig } from "../service";

const DeliverSetModal = ({ handleCancel }) => {

  const [open, setOpen] = useState(false);

  const [form] = Form.useForm();

  const [deliverList, setDeliverList] = useState([]);

  useEffect(() => {
    setOpen(true);
    getShippingConfig();
  }, [])

  const getShippingConfig = async () => {
    const { success, data } = await getShippingConfigList();
    if (success) {
      setDeliverList(data);
      const obj = find(data, ['prompt', 'shipping_config']);
      if(obj) {
         form.setFieldsValue({
          configStatus: obj.configStatus
         })
      }
    }
  }

  //保存数据
  const saveData = async (val) => {
    const obj = find(deliverList, ['prompt', 'shipping_config']);
    if(obj) {
      obj.configStatus = val.configStatus;
   }
    const { success } = await saveOrUpdateVoiceConfig(deliverList);
    if (success) {
      message.success("操作成功");
      setOpen(false);
    }
  }

  const onOk = () => {
     form.validateFields().then(val => {
      saveData(val)
     }).catch(err => {
      console.log(err, 'err');
     })
  }

  const onCancel = () => {
    setOpen(false);
  }

  const afterClose = () => {
    handleCancel();
  }

  return (
    <CommonModal
      title="发货设置"
      width="520px"
      open={open}
      onOk={onOk}
      onCancel={onCancel}
      afterClose={afterClose}
    >
      <Alert style={{ marginBottom: '16px' }} description={<div>注意：转库存商品只针对<span className='common-color9'>未采购备货并且未付款</span>的商品</div>} />
      <Form
        name="deliver-set-modal-form"
        form={form}
        autoComplete='false'
      >
        <Form.Item name="configStatus" label="强制发货（未拿货商品）" rules={[{ required: true, message: '请选择' }]}>
          <Radio.Group>
            <Space size={16}>
              <Radio value="close">采购发货（自动扣减备货金额）</Radio>
              <Radio value="open">转库存发货（不收取备货金额）</Radio>
            </Space>
          </Radio.Group>
        </Form.Item>
      </Form>
    </CommonModal>
  )
}

export default DeliverSetModal;